package com.xmall.order.define.config;

import com.xmall.msg.queue.OrderModule;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class AmqpShareExchangeConfig {

    @Resource
    private RabbitAdmin rabbitAdmin;

    /**
     * 订单取消流向
     * 订单取消：路由键（order.order.cancel.key） --> 广播交换机（order.order.cancel.fanout.exchange）
     *                                        --> 队列（order.order.cancel.queue）
     */
    @Bean
    public Exchange orderCancelFanoutExchange() {
        FanoutExchange exchange = new FanoutExchange(OrderModule.OrderCancel.ORDER_CANCEL_FANOUT_EXCHANGE);
        rabbitAdmin.declareExchange(exchange);
        return exchange;
    }
    @Bean
    public Queue orderCancelQueue() {
        Queue queue = new Queue(OrderModule.OrderCancel.ORDER_CANCEL_QUEUE, true, false, false);
        rabbitAdmin.declareQueue(queue);
        return queue;
    }
    @Bean
    public Binding orderCancelBinding() {
        Binding binding = BindingBuilder.bind(orderCancelQueue()).to(orderCancelFanoutExchange()).with(OrderModule.OrderCancel.ORDER_CANCEL_ROUTING_KEY).noargs();
        rabbitAdmin.declareBinding(binding);
        return binding;
    }

    /**
     * 订单支付成功流向
     * 订单支付成功：路由键（order.order.pay.success.key） --> 广播交换机（order.order.pay.success.fanout.exchange）
     *                                                --> 队列（order.order.pay.success.queue）
     */
    @Bean
    public Exchange orderPaySuccessFanoutExchange() {
        FanoutExchange exchange = new FanoutExchange(OrderModule.OrderPaySuccess.ORDER_PAY_SUCCESS_FANOUT_EXCHANGE);
        rabbitAdmin.declareExchange(exchange);
        return exchange;
    }
    @Bean
    public Queue orderPaySuccessQueue() {
        Queue queue = new Queue(OrderModule.OrderPaySuccess.ORDER_PAY_SUCCESS_QUEUE, true, false, false);
        rabbitAdmin.declareQueue(queue);
        return queue;
    }
    @Bean
    Binding orderPaySuccessBinding() {
        Binding binding = BindingBuilder.bind(orderPaySuccessQueue()).to(orderPaySuccessFanoutExchange()).with(OrderModule.OrderPaySuccess.ORDER_PAY_SUCCESS_ROUTING_KEY).noargs();
        rabbitAdmin.declareBinding(binding);
        return binding;
    }
}
